import { getAreaData } from "@/api";
import type { IAreaDataResultItem } from "@/api/indexTypes";
import { CacheEnum } from "@/enums/cacheEnum";

export function getLocalAreaData() {
  return uni.getStorageSync(CacheEnum.localareaData) as { [x: number]: IAreaDataResultItem[] };
}

export function setLocalAreaData(oVal: Recordable, nVal: Recordable) {
  return uni.setStorageSync(CacheEnum.localareaData, { ...oVal, ...nVal });
}

/**
 * @description 获取省市区数据
 * @date 04/03/2024
 * @export
 * @param {number} [pid=0]
 * @returns {*}  {Promise<IAreaDataResultItem[]>}
 */
export async function getCityData(pid: number = 0): Promise<IAreaDataResultItem[]> {
  return new Promise(async (resolve, reject) => {
    const oVal = getLocalAreaData();
    const item = oVal[pid];
    if (item) return resolve(item)
    try {
      const res = await getAreaData(pid);
      setLocalAreaData(oVal, { [pid]: res });
      resolve(res)
    } catch (error) {
      reject(error)
    }
  })
}